/*
 * EmpresaCadastrar.java
 *
 * Created on 12/02/2009, 15:50:39
 * Copyright Jaime Junior
 * Modified on last 31/08/2009, 15:57
 * Elizabete Yanase Hirabara Bento
 *
 */
package Adecot.Empresas;

import Adecot.*;
import Controller.CidadeBO;
import Controller.EmpresaBO;
import Controller.EstadoBO;
import Controller.Facade.IceDecorator;
import Controller.Facade.ValidaFacade;
import Model.Cidade;
import Model.Empresa;
import Model.Endereco;
import Report.XML.CriaQuery;
import Report.XML.ManipulaXML;
import Report.XML.Relatorio;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import com.icesoft.faces.component.ext.HtmlGraphicImage;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlOutputText;
import com.icesoft.faces.component.ext.HtmlSelectOneMenu;
import com.icesoft.faces.component.ext.KeyEvent;
import com.icesoft.faces.component.jsfcl.data.DefaultSelectedData;
import com.icesoft.faces.component.jsfcl.data.DefaultSelectionItems;
import com.icesoft.faces.component.jsfcl.data.PopupBean;
import com.icesoft.faces.component.panelpopup.PanelPopup;
import com.icesoft.faces.component.selectinputtext.SelectInputText;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.validator.DoubleRangeValidator;

public class EmpresaCadastrar extends AbstractPageBean {
   // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

   private int __placeholder;

   /**
    * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
    * This method is automatically generated, so any user-specified code inserted
    * here is subject to being replaced.</p>
    */
   private void _init() throws Exception {
   }
   /**
    * atributo que para a validação para objetos identicos,
    * utilizado quando há consulta e alteração de associado
    */
   private boolean parar;

   public boolean isParar() {
      return parar;
   }

   public void setParar(boolean parar) {
      this.parar = parar;
   }
   private DefaultSelectionItems msgPainelConsulta = new DefaultSelectionItems();

   public DefaultSelectionItems getMsgPainelConsulta() {
      return msgPainelConsulta;
   }

   public void setMsgPainelConsulta(DefaultSelectionItems consulta) {
      this.msgPainelConsulta = consulta;
   }
   private DefaultSelectedData estadoSelecionado = new DefaultSelectedData();

   public DefaultSelectedData getEstadoSelecionado() {
      return estadoSelecionado;
   }

   public void setEstadoSelecionado(DefaultSelectedData dsd) {
      this.estadoSelecionado = dsd;
   }
   private DefaultSelectionItems estados = new DefaultSelectionItems();

   public DefaultSelectionItems getEstados() {
      return estados;
   }

   public void setEstados(DefaultSelectionItems dsi) {
      this.estados = dsi;
   }
   private HtmlSelectOneMenu comboEstado = new HtmlSelectOneMenu();

   public HtmlSelectOneMenu getComboEstado() {
      return comboEstado;
   }

   public void setComboEstado(HtmlSelectOneMenu hsom) {
      this.comboEstado = hsom;
   }
   private DefaultSelectedData cidadeSelecionada = new DefaultSelectedData();

   public DefaultSelectedData getCidadeSelecionada() {
      return cidadeSelecionada;
   }

   public void setCidadeSelecionada(DefaultSelectedData dsd) {
      this.cidadeSelecionada = dsd;
   }
   private DefaultSelectionItems cidades = new DefaultSelectionItems();

   public DefaultSelectionItems getCidades() {
      return cidades;
   }

   public void setCidades(DefaultSelectionItems dsi) {
      this.cidades = dsi;
   }
   private HtmlSelectOneMenu comboCidade = new HtmlSelectOneMenu();

   public HtmlSelectOneMenu getComboCidade() {
      return comboCidade;
   }

   public void setComboCidade(HtmlSelectOneMenu hsom) {
      this.comboCidade = hsom;
   }
   private HtmlInputText campoNome = new HtmlInputText();

   public HtmlInputText getCampoNome() {
      return campoNome;
   }

   public void setCampoNome(HtmlInputText hit) {
      this.campoNome = hit;
   }
   private HtmlInputText cnpj = new HtmlInputText();

   public HtmlInputText getCnpj() {
      return cnpj;
   }

   public void setCnpj(HtmlInputText hit) {
      this.cnpj = hit;
   }
   private HtmlInputText inscEstadual = new HtmlInputText();

   public HtmlInputText getInscEstadual() {
      return inscEstadual;
   }

   public void setInscEstadual(HtmlInputText hit) {
      this.inscEstadual = hit;
   }
   private HtmlInputText campoEndereco = new HtmlInputText();

   public HtmlInputText getCampoEndereco() {
      return campoEndereco;
   }

   public void setCampoEndereco(HtmlInputText hit) {
      this.campoEndereco = hit;
   }
   private HtmlInputText campoBairro = new HtmlInputText();

   public HtmlInputText getCampoBairro() {
      return campoBairro;
   }

   public void setCampoBairro(HtmlInputText hit) {
      this.campoBairro = hit;
   }
   private HtmlInputText campoComplemento = new HtmlInputText();

   public HtmlInputText getCampoComplemento() {
      return campoComplemento;
   }

   public void setCampoComplemento(HtmlInputText hit) {
      this.campoComplemento = hit;
   }
   private HtmlInputText campoCep = new HtmlInputText();

   public HtmlInputText getCampoCep() {
      return campoCep;
   }

   public void setCampoCep(HtmlInputText hit) {
      this.campoCep = hit;
   }
   private HtmlInputText campoTelefone = new HtmlInputText();

   public HtmlInputText getCampoTelefone() {
      return campoTelefone;
   }

   public void setCampoTelefone(HtmlInputText hit) {
      this.campoTelefone = hit;
   }
   private HtmlInputText campoFax = new HtmlInputText();

   public HtmlInputText getCampoFax() {
      return campoFax;
   }

   public void setCampoFax(HtmlInputText hit) {
      this.campoFax = hit;
   }
   private HtmlInputText campoEmail = new HtmlInputText();

   public HtmlInputText getCampoEmail() {
      return campoEmail;
   }

   public void setCampoEmail(HtmlInputText hit) {
      this.campoEmail = hit;
   }
   private PopupBean panelPopup1Bean = new PopupBean();

   public PopupBean getPanelPopup1Bean() {
      return panelPopup1Bean;
   }

   public void setPanelPopup1Bean(PopupBean pb) {
      this.panelPopup1Bean = pb;
   }
   private PanelPopup painelSair = new PanelPopup();

   public PanelPopup getPainelSair() {
      return painelSair;
   }

   public void setPainelSair(PanelPopup pp) {
      this.painelSair = pp;
   }
   private PopupBean panelPopup1Bean1 = new PopupBean();

   public PopupBean getPanelPopup1Bean1() {
      return panelPopup1Bean1;
   }

   public void setPanelPopup1Bean1(PopupBean pb) {
      this.panelPopup1Bean1 = pb;
   }
   private HtmlCommandButton botaoConsultaCancelar = new HtmlCommandButton();

   public HtmlCommandButton getBotaoConsultaCancelar() {
      return botaoConsultaCancelar;
   }

   public void setBotaoConsultaCancelar(HtmlCommandButton hcb) {
      this.botaoConsultaCancelar = hcb;
   }
   private PanelPopup painelConsulta = new PanelPopup();

   public PanelPopup getPainelConsulta() {
      return painelConsulta;
   }

   public void setPainelConsulta(PanelPopup pp) {
      this.painelConsulta = pp;
   }
   private HtmlCommandButton botaoCadastrar1 = new HtmlCommandButton();

   public HtmlCommandButton getBotaoCadastrar1() {
      return botaoCadastrar1;
   }

   public void setBotaoCadastrar1(HtmlCommandButton hcb) {
      this.botaoCadastrar1 = hcb;
   }
   private HtmlCommandButton botaoAvisoSim = new HtmlCommandButton();

   public HtmlCommandButton getBotaoAvisoSim() {
      return botaoAvisoSim;
   }

   public void setBotaoAvisoSim(HtmlCommandButton hcb) {
      this.botaoAvisoSim = hcb;
   }
   private HtmlCommandButton botaoAvisoNao = new HtmlCommandButton();

   public HtmlCommandButton getBotaoAvisoNao() {
      return botaoAvisoNao;
   }

   public void setBotaoAvisoNao(HtmlCommandButton hcb) {
      this.botaoAvisoNao = hcb;
   }
   private PanelPopup painelAviso = new PanelPopup();

   public PanelPopup getPainelAviso() {
      return painelAviso;
   }

   public void setPainelAviso(PanelPopup pp) {
      this.painelAviso = pp;
   }
   private HtmlCommandButton botaoConsultaOk = new HtmlCommandButton();

   public HtmlCommandButton getBotaoConsultaOk() {
      return botaoConsultaOk;
   }

   public void setBotaoConsultaOk(HtmlCommandButton hcb) {
      this.botaoConsultaOk = hcb;
   }
   private SelectInputText campoConsulta = new SelectInputText();

   public SelectInputText getCampoConsulta() {
      return campoConsulta;
   }

   public void setCampoConsulta(SelectInputText sit) {
      this.campoConsulta = sit;
   }
   private HtmlCommandButton botaoLimpar = new HtmlCommandButton();

   public HtmlCommandButton getBotaoLimpar() {
      return botaoLimpar;
   }

   public void setBotaoLimpar(HtmlCommandButton hcb) {
      this.botaoLimpar = hcb;
   }
   private HtmlCommandButton botaoAlterar = new HtmlCommandButton();

   public HtmlCommandButton getBotaoAlterar() {
      return botaoAlterar;
   }

   public void setBotaoAlterar(HtmlCommandButton hcb) {
      this.botaoAlterar = hcb;
   }
   private HtmlCommandButton botaoDesativar = new HtmlCommandButton();

   public HtmlCommandButton getBotaoDesativar() {
      return botaoDesativar;
   }

   public void setBotaoDesativar(HtmlCommandButton hcb) {
      this.botaoDesativar = hcb;
   }
   private HtmlInputText razaoSocial = new HtmlInputText();

   public HtmlInputText getRazaoSocial() {
      return razaoSocial;
   }

   public void setRazaoSocial(HtmlInputText hit) {
      this.razaoSocial = hit;
   }
   private PopupBean panelPopup1Bean2 = new PopupBean();

   public PopupBean getPanelPopup1Bean2() {
      return panelPopup1Bean2;
   }

   public void setPanelPopup1Bean2(PopupBean pb) {
      this.panelPopup1Bean2 = pb;
   }
   private PanelPopup painelMensagem = new PanelPopup();

   public PanelPopup getPainelMensagem() {
      return painelMensagem;
   }

   public void setPainelMensagem(PanelPopup pp) {
      this.painelMensagem = pp;
   }
   private DoubleRangeValidator doubleRangeValidator1 = new DoubleRangeValidator();

   public DoubleRangeValidator getDoubleRangeValidator1() {
      return doubleRangeValidator1;
   }

   public void setDoubleRangeValidator1(DoubleRangeValidator drv) {
      this.doubleRangeValidator1 = drv;
   }
   private HtmlCommandButton botaoMensagemOk = new HtmlCommandButton();

   public HtmlCommandButton getBotaoMensagemOk() {
      return botaoMensagemOk;
   }

   public void setBotaoMensagemOk(HtmlCommandButton hcb) {
      this.botaoMensagemOk = hcb;
   }
   private HtmlOutputText msgMensagemOperacao = new HtmlOutputText();

   public HtmlOutputText getMsgMensagemOperacao() {
      return msgMensagemOperacao;
   }

   public void setMsgMensagemOperacao(HtmlOutputText hot) {
      this.msgMensagemOperacao = hot;
   }
   private HtmlOutputText msgMensagemResultado = new HtmlOutputText();

   public HtmlOutputText getMsgMensagemResultado() {
      return msgMensagemResultado;
   }

   public void setMsgMensagemResultado(HtmlOutputText hot) {
      this.msgMensagemResultado = hot;
   }
   private HtmlGraphicImage imagemSituacao = new HtmlGraphicImage();

   public HtmlGraphicImage getImagemSituacao() {
      return imagemSituacao;
   }

   public void setImagemSituacao(HtmlGraphicImage hgi) {
      this.imagemSituacao = hgi;
   }

   // </editor-fold>
   /**
    * <p>Construct a new Page bean instance.</p>
    */
   public EmpresaCadastrar() {
   }

   /**
    * <p>Callback method that is called whenever a page is navigated to,
    * either directly via a URL, or indirectly via page navigation.
    * Customize this method to acquire resources that will be needed
    * for event handlers and lifecycle methods, whether or not this
    * page is performing post back processing.</p>
    *
    * <p>Note that, if the current request is a postback, the property
    * values of the components do <strong>not</strong> represent any
    * values submitted with this request.  Instead, they represent the
    * property values that were saved for this view when it was rendered.</p>
    */
   @Override
   public void init() {
      // Perform initializations inherited from our superclass
      super.init();
      // Perform application initialization that must complete
      // *before* managed components are initialized
      // TODO - add your own initialiation code here

      // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
      // Initialize automatically managed components
      // *Note* - this logic should NOT be modified
      try {
         _init();
      } catch (Exception e) {
         log("EmpresaCadastrar Initialization Failure", e);
         throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
      }

      estados.clear();
      this.setEstados(new IceDecorator(EstadoBO.class).montaCombo());
      limparCampos();
      painelSair.setRendered(false);
      painelConsulta.setRendered(false);
      painelAviso.setRendered(false);
      botaoAlterar.setDisabled(true);
      painelMensagem.setRendered(false);
      botaoAlterar.setDisabled(true);
      setParar(false);

   // </editor-fold>
   // Perform application initialization that must complete
   // *after* managed components are initialized
   // TODO - add your own initialization code here
   }

   /**
    * <p>Callback method that is called after the component tree has been
    * restored, but before any event processing takes place.  This method
    * will <strong>only</strong> be called on a postback request that
    * is processing a form submit.  Customize this method to allocate
    * resources that will be required in your event handlers.</p>
    */
   @Override
   public void preprocess() {
   }

   /**
    * <p>Callback method that is called just before rendering takes place.
    * This method will <strong>only</strong> be called for the page that
    * will actually be rendered (and not, for example, on a page that
    * handled a postback and then navigated to a different page).  Customize
    * this method to allocate resources that will be required for rendering
    * this page.</p>
    */
   @Override
   public void prerender() {
   }

   /**
    * <p>Callback method that is called after rendering is completed for
    * this request, if <code>init()</code> was called (regardless of whether
    * or not this was the page that was actually rendered).  Customize this
    * method to release resources acquired in the <code>init()</code>,
    * <code>preprocess()</code>, or <code>prerender()</code> methods (or
    * acquired during execution of an event handler).</p>
    */
   @Override
   public void destroy() {
   }

   /**
    * <p>Retornar uma referência para o Bean de dados limitados.</p>
    *
    * @retorna uma referência para o bean de dados limitados
    */
   protected SessionBean1 getSessionBean1() {
      return (SessionBean1) getBean("SessionBean1");
   }

   /**
    * <p>Retornar uma referência para o Bean de dados limitados.</p>
    *
    * @retorna uma referência para o bean de dados limitados
    */
   protected RequestBean1 getRequestBean1() {
      return (RequestBean1) getBean("RequestBean1");
   }

   /**
    * <p>Retornar uma referência para o Bean de dados limitados.</p>
    *
    * @retorna uma referência para o bean de dados limitados
    */
   protected ApplicationBean1 getApplicationBean1() {
      return (ApplicationBean1) getBean("ApplicationBean1");
   }

   public void comboEstado_processValueChange(ValueChangeEvent vce) {
      this.setCidades(new IceDecorator(CidadeBO.class).montaComboVinculado("estado",
              "codEstado", Integer.parseInt(comboEstado.getValue().toString())));
   }

   public String botaoCadastrar1_action() {

      try {
         Empresa empresa = (Empresa) getBean("Empresa");
         Endereco end = (Endereco) getBean("Endereco");

         Cidade city = (Cidade) new IceDecorator(CidadeBO.class).retornaObjetoCodigo("codCidade",
                 Integer.parseInt(comboCidade.getValue().toString()));

         end.setCidade(city);
         empresa.setEndereco(end);

         if (botaoDesativar.getImage().equals("/resources/botaoInativo.jpg")) {
            empresa.setAtivo(true);
         } else {
            empresa.setAtivo(false);
         }
empresa.setAtivo(true);
         new IceDecorator(EmpresaBO.class).salvar(empresa);
         limparCampos();
         botaoAlterar.setDisabled(true);
         painelMensagem.setRendered(true);
         msgMensagemResultado.setValue("Operação Efetuada Com Sucesso");

      } catch (Exception e) {
         painelMensagem.setRendered(true);
         msgMensagemResultado.setValue("Erro Ao Efetuar Operação");
         msgMensagemOperacao.setValue("Verfificar se há: ".concat(e.getMessage()));
      }
      return null;
   }

   public String botaoConsultar_action() {
      painelConsulta.setRendered(true);
      return null;
   }

   public void campoConsulta_processValueChange(ValueChangeEvent vce) {
      try {
         this.setMsgPainelConsulta(new IceDecorator(EmpresaBO.class).consultaIncremental("nome", campoConsulta.getValue().toString()));
      } catch (Exception e) {
         setMsgPainelConsulta(msgPainelConsulta);
      }
   }

   public void limparCampos() {

      FacesContext.getCurrentInstance().getExternalContext().getRequestMap().remove("Empresa");
      FacesContext.getCurrentInstance().getExternalContext().getRequestMap().remove("Endereco");

      campoBairro.resetValue();
      campoCep.resetValue();
      cnpj.resetValue();
      campoComplemento.resetValue();
      campoConsulta.resetValue();
      campoEmail.resetValue();
      campoEndereco.resetValue();
      campoFax.resetValue();
      inscEstadual.resetValue();
      razaoSocial.resetValue();
      campoNome.resetValue();
      campoTelefone.resetValue();
      comboEstado.setValue(new Integer(16));
      setCidades(new IceDecorator(CidadeBO.class).montaComboVinculado("estado", "codEstado",
              Integer.parseInt(comboEstado.getValue().toString())));
      comboCidade.setValue(2788);
      botaoAlterar.setDisabled(true);
      habilitarCampos();
      setParar(false);
   }

   public void habilitarCampos() {
      campoBairro.setDisabled(false);
      campoCep.setDisabled(false);
      campoComplemento.setDisabled(false);
      cnpj.setDisabled(false);
      campoEmail.setDisabled(false);
      campoFax.setDisabled(false);
      inscEstadual.setDisabled(false);
      campoTelefone.setDisabled(false);
      campoNome.setDisabled(false);
      comboCidade.setDisabled(false);
      comboEstado.setDisabled(false);
      campoEndereco.setDisabled(false);
      razaoSocial.setDisabled(false);


   }

   public void desabilitarCampos() {
      campoBairro.setDisabled(true);
      campoCep.setDisabled(true);
      campoComplemento.setDisabled(true);
      cnpj.setDisabled(true);
      campoEmail.setDisabled(true);
      campoFax.setDisabled(true);
      inscEstadual.setDisabled(true);
      campoTelefone.setDisabled(true);
      campoNome.setDisabled(true);
      comboCidade.setDisabled(true);
      comboEstado.setDisabled(true);
      campoEndereco.setDisabled(true);
      razaoSocial.setDisabled(true);
   }

   public String botaoLimpar_action() {
      setCidades(new IceDecorator(CidadeBO.class).montaComboVinculado("estado", "codEstado", 16));
      comboCidade.setValue(1);
      limparCampos();
      return null;
   }

   public String botaoAlterar_action() {
      habilitarCampos();
      setParar(true);
      return null;
   }

   public String botaoSairSim_action() {
      //return null means stay on the same page
      return "menu";
   }

   public String botaoSairNao_action() {
      painelSair.setRendered(false);
      return null;
   }

   public String botaoConsultaOk_action() {

      try {
         Empresa empresa = (Empresa) new IceDecorator(EmpresaBO.class).retornaObjeto("nome", campoConsulta.getValue().toString());
         limparCampos();
         setBean("Empresa", empresa);
         setBean("Endereco", empresa.getEndereco());

         comboEstado.setValue(new Integer(empresa.getEndereco().getCidade().getEstado().getCodEstado()));

         setCidades(new IceDecorator(CidadeBO.class).montaComboVinculado("estado", "codEstado",
                 Integer.parseInt(comboEstado.getValue().toString())));

         comboCidade.setValue(new Integer(empresa.getEndereco().getCidade().getCodCidade()));

         painelConsulta.setRendered(false);
         desabilitarCampos();
         if (empresa.getAtivo() == true) {
            botaoDesativar.setImage("/resources/botaoInativo.png");
            imagemSituacao.setValue("/resources/botaoSituacaoAtivo.png");
            imagemSituacao.setTitle("Ativo");

         } else {
            botaoDesativar.setImage("/resources/botaoAtivo.png");
            imagemSituacao.setValue("/resources/botaoSituacaoInativo.png");
            imagemSituacao.setTitle("Inativo");
         }
         botaoAlterar.setDisabled(false);

      } catch (Exception exc) {
         painelAviso.setRendered(true);
      }
      return null;
   }

   public String botaoConsultaCancelar_action() {
      painelConsulta.setRendered(false);
      return null;
   }

   public String botaoAvisoSim_action() {
      painelAviso.setRendered(false);
      return null;
   }

   public String botaoAvisoNao_action() {
      painelAviso.setRendered(false);
      painelConsulta.setRendered(false);
      return null;
   }

   public String botaoMensagemOk_action() {
      painelMensagem.setRendered(false);
      return null;
   }

   public String botaoSair_action() {
      painelSair.setRendered(true);
      return null;
   }

   public String botaoDesativar_action() {
      if (botaoDesativar.getImage().equals("/resources/botaoInativo.png")) {
         botaoDesativar.setImage("/resources/botaoAtivo.png");
         botaoDesativar.setTitle("Ativar");
         imagemSituacao.setValue("/resources/botaoSituacaoInativo.png");
         imagemSituacao.setTitle("Inativo");
         return null;
      } else if (botaoDesativar.getImage().equals("/resources/botaoAtivo.png")) {
         botaoDesativar.setImage("/resources/botaoInativo.png");
         botaoDesativar.setTitle("Desativar");
         imagemSituacao.setValue("/resources/botaoSituacaoAtivo.png");
         imagemSituacao.setTitle("Ativo");
         return null;
      }
      return null;
   }

   public String botaoNovo_action() {
      setCidades(new IceDecorator(CidadeBO.class).montaComboVinculado("estado", "codEstado", 16));
      comboCidade.setValue(1);
      limparCampos();
      return null;
   }

   public void validateCnpj(FacesContext context, UIComponent component, Object value) {
      new ValidaFacade().validateCnpj(context, component, value, EmpresaBO.class, parar);
   }

   public void validateCampoUnico(FacesContext context, UIComponent component, Object value) {
      new ValidaFacade().validateCampoUnico(context, component, value, EmpresaBO.class, parar);
   }

   public String botaoImprimir_action() {
      ManipulaXML manipulaXML = new ManipulaXML();
      CriaQuery criaQuery = new CriaQuery();
      Relatorio relatorio = new Relatorio();
      try {
         manipulaXML.modificaXML("Relatorios\\EmpresaCompleto", criaQuery.criaQueryEmpresaCompleto(campoNome.getValue().toString()));
         relatorio.geraJrprint("Relatorios\\EmpresaCompleto");
         relatorio.geraRelatorioPDF("Relatorios\\EmpresaCompleto");
         java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
         desktop.open(new File("Relatorios\\EmpresaCompleto.pdf"));
      } catch (Exception e) {
      }
      return null;
   }
}